package com.lez.kotlincoroutine.activity

import android.os.AsyncTask
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.lez.kotlincoroutine.R
import com.lez.kotlincoroutine.api.userServiceApi
import kotlinx.coroutines.*

/**
 * 协程作用域之---MainScope
 * 在onDestroy()方法中可以取消协程
 *
 */
class MainScopeActivity :AppCompatActivity() {

    private val mainScope = MainScope()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val nameTextView = findViewById<TextView>(R.id.nameTextView)
        nameTextView.text = "Jack"

        //协程版网络请求
        val submitButton = findViewById<Button>(R.id.submitButton).also {
            it.setOnClickListener{
                mainScope.launch(Dispatchers.Main) {  //外边称为父协程
                    delay(10000)
                    val bannerResponse = userServiceApi.getBanner();  //retrofit会自动识别suspend函数，开启协程
                    nameTextView.text = bannerResponse.data[0].title
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mainScope.cancel()  //协程取消时候 会抛出异常
    }
}